package com.wjx.zk;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZkClientTest {

    public static void main(String[] args) {
        try {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            ZkClient zk = new ZkClient("192.168.11.128:2182,192.168.11.128:2183,192.168.11.128:2184");
            System.out.println("zk connect");

            zk.createPersistent("/test/test1", true);

            zk.deleteRecursive("/test");

            String path = "/test";
            IZkChildListener listener = new IZkChildListener() {
                @Override
                public void handleChildChange(String parent, List<String> list) throws Exception {
                    System.out.println("ChildChange parent path: " + parent + ",current children :" + list);
                }
            };
            zk.subscribeChildChanges(path, listener);

            zk.createPersistent(path);
            zk.createPersistent(path + "/c1");
            zk.delete(path + "/c1");
            zk.delete(path);
            zk.unsubscribeChildChanges(path, listener);
            Thread.sleep(1000);

            System.out.println("----------------data change");
            zk.subscribeDataChanges(path, new IZkDataListener() {
                @Override
                public void handleDataChange(String s, Object data) throws Exception {
                    System.out.println("DataChanges path:" + s + ",new data: " + data);
                }

                @Override
                public void handleDataDeleted(String s) throws Exception {
                    System.out.println("DataChanges path " + s + " deleted");
                }
            });

            zk.createPersistent(path, "1111");
            System.out.println("read data " + zk.readData(path));
            zk.writeData(path, "222");
            zk.delete(path);

            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
